import random
import time
import uuid

from django.shortcuts import redirect
from django.views import View
from alipay import AliPay
from alipay.utils import AliPayConfig
from .models import *
from userInfo.models import Address
from common.token_dec import token_dec
# 导入响应数据函数
from common.respond.res import res

# Create your views here.

# 应用私钥
app_private_key_string = open("pay/key/app_private_key.pem").read()
# 支付宝公钥
alipay_public_key_string = open("pay/key/alipay_public_key.pem").read()

# 实例化对象
alipay_pay = AliPay(
    appid="2021000122689885",
    app_notify_url=None,  # 默认回调url
    app_private_key_string=app_private_key_string,
    # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
    alipay_public_key_string=alipay_public_key_string,
    sign_type="RSA2",  # RSA 或者 RSA2
    debug=True,  # 默认False
    verbose=False,  # useful for debugging
    config=AliPayConfig(timeout=15)  # 超时
)


# 创建订单
@token_dec
def create_order(request):
    user = request.myuser
    data = eval(request.body.decode())
    key_id = int(random.random() * 999999)  # 同一个订单
    order_time = int(time.time()) + 600
    # 判断有没有默认地址
    if not Address.objects.filter(uid=user['userId'], isDefault=True).exists():
        return res(400, "订单创建失败！", {'err': "请添加默认收货地址"})
    if isinstance(eval(data['goodsList']), dict):
        address_id = Address.objects.get(uid=user['userId'], isDefault=True).address_id
        order_number = str(uuid.uuid4())  # 订单号
        price = float(eval(data['goodsList'])['goods_price']) * float(eval(data['goodsList'])['num'])  # 价格
        OrderInfo(order_id=order_number, user_id=user['userId'], address_id=address_id,
                  price=price, goods_info=eval(data['goodsList']), status="1",
                  key_id=key_id, order_time=order_time, num=eval(data['goodsList'])["num"]).save()
        return res(200, "订单创建成功！", {"success": True, "key_id": key_id})
    elif isinstance(eval(data['goodsList']), list):
        address_id = Address.objects.get(uid=user['userId'], isDefault=True).address_id
        for goods_item in eval(data['goodsList']):
            order_number = str(uuid.uuid4())  # 订单号
            price = float(goods_item['goods_price']) * float(goods_item['num'])  # 价格
            OrderInfo(order_id=order_number, user_id=user['userId'], address_id=address_id,
                      price=price, goods_info=goods_item, status="1",
                      key_id=key_id, order_time=order_time, num=goods_item["num"]).save()

        return res(200, "订单创建成功！", {"success": True, "key_id": key_id})


# 获取订单
@token_dec
def get_order(request):
    user = request.myuser
    order_id = request.GET.get("order_id", None)
    key_id = request.GET.get("key_id", None)
    order_list = []
    timer = ""
    # 单个订单
    if key_id is None:
        order_list = list(OrderInfo.objects.filter(order_id=order_id).values())
        for order_item in order_list:
            order_item['goods_info'] = eval(order_item['goods_info'])
        timer = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(order_item['order_time'])))
    elif order_id is None:
        order_list = list(OrderInfo.objects.filter(key_id=key_id).values())
        for order_item in order_list:
            order_item['goods_info'] = eval(order_item['goods_info'])
            # if int(time.time()) > int(order_item['order_time']):
            #     OrderInfo.objects.filter(key_id=key_id).update(status="0")
            #     return res(200, "获取失败！", {"success": "订单已失效，请重新下单！"})
            timer = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(order_item['order_time'])))
    address = Address.objects.filter(uid=user['userId'], isDefault=True).values()
    return res(200, "获取成功！", {'order_info': order_list, "address": address[0], "time": timer, "key_id": key_id})


# 获取不同状态的商品
@token_dec
def get_order_status(request):
    user = request.myuser
    status = request.GET.get("status", None)
    # 将所有过期的订单处理
    order_all = OrderInfo.objects.all()
    for order_all_item in order_all:
        if int(time.time()) > int(order_all_item.order_time):
            if order_all_item.status == "1":
                order_all_item.status = 0
                order_all_item.save()
    order_list = list(OrderInfo.objects.filter(user_id=user['userId'], status=status).values())
    for order_item in order_list:
        order_item['goods_info'] = eval(order_item['goods_info'])
    return res(200, "获取成功！", {'order_list': order_list, "success": True})


class PayGoods(View):
    def get(self, request):
        key_id = request.GET.get("key_id")
        price = request.GET.get("price")
        order_string = alipay_pay.api_alipay_trade_page_pay(
            subject="用户下单",
            out_trade_no=key_id,
            total_amount=price,  # 交易金额(单位是元，保留两位小数)
            return_url="http://192.168.127.4:5000/pay/check_order",  # 支付成功之后,跳转的页面
            notify_url=None  # 可选, 不填则使用默认notify url
        )
        # 支付地址 rdswbn6270@sandbox.com
        pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
        # 返回响应
        return res(200, "订单创建成功！", {'alipay_url': pay_url})



# 订单支付
class CheckPayView(View):
    def get(self, request):
        data = request.GET.dict()
        signtrue = data.pop('sign')
        success = alipay_pay.verify(data, signtrue)
        if success:
            # 支付成功就更改订单信息
            order_list = OrderInfo.objects.filter(key_id=data['out_trade_no'])
            for order_list_item in order_list:
                order_list_item.status = 2
                order_list_item.save()
            # 支付成功
            return redirect("http://192.168.127.4:5173/#/pages/pay/success/success")
        # 支付失败
        return redirect("http://192.168.127.4:5173/#/pages/pay/failure/failure")
